package org.linlinjava.litemall.wx.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.db.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class ExpressTokenTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);

    public ExpressTokenTask(String id, long delayInMilliseconds) {
        super(id, delayInMilliseconds);
    }

    public ExpressTokenTask() {
        this("ExpressTokenTask", SystemConfig.getLitemallMallExpressToken() * 60 * 1000);
    }


    @Override
    public void run() {
        RedisService redisService = BeanUtil.getBean(RedisService.class);
        try {
            URL url = new URL("http://www.baidu.com/s?ie=UTF-8&wd=%E5%BF%AB%E9%80%92%E6%9F%A5%E8%AF%A2");
            URLConnection urlConnection = url.openConnection();
            InputStream in = urlConnection.getInputStream();
            try {

                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = in.read(buffer)) != -1) {
                    output.write(buffer, 0, len);
                }
                String inputString = output.toString();
                String apiUrl = regexFind("checkUrl: \"(.+?)\"", inputString);

                String args = regexFind("args: \"(.+?)\"", inputString);
                redisService.set("expressUrl", apiUrl+args);


            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private synchronized String regexFind(String regex, String input) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            return matcher.group(1);

        }
        return null;
    }
}
